package com.niiwoo.civet.trade.service.local.activity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.activity.event.constant.BizEventRabbitConstant;
import com.niiwoo.activity.event.dto.request.*;
import com.niiwoo.activity.event.enums.*;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectBorrowerSummary;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestorPlan;
import com.niiwoo.civet.trade.dao.mapper.*;
import com.niiwoo.civet.trade.dto.ProjectBorrowerPlanNewDTO;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.common.TradeBatchTransOrderDTO;
import com.niiwoo.civet.trade.dto.newRefund.RefundStateDTO;
import com.niiwoo.civet.trade.enums.ProjectInvestOrderStatusEnum;
import com.niiwoo.civet.trade.enums.ProjectStatusEnum;
import com.niiwoo.civet.trade.enums.RepayStatusEnum;
import com.niiwoo.civet.trade.service.loan.SpeedLoanDubboService;
import com.niiwoo.civet.trade.service.local.newRefund.refundDeal.core.FeeCalcForRefundService;
import com.niiwoo.civet.trade.service.local.project.ProjectLocalService;
import com.niiwoo.civet.user.dto.response.UserSpeedCreditInfoDTO;
import com.niiwoo.civet.user.service.UserCreditDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.utils.IdCardUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 交易中心-活动中心相关MQ消息通知
 * 
 * @author: liaozuliang
 * @date: 2018/3/26
 */
@Service
@Slf4j
public class ActivityEventService {
	
    @Autowired
    private ProjectMapper projectMapper;
    
    @Autowired
    private ProjectMapperExt projectMapperExt;
    
    @Autowired
    private ProjectBorrowerPlanNewMapperExt projectBorrowerPlanNewMapperExt;
    
    @Autowired
    private ProjectInvestOrderMapperExt projectInvestOrderMapperExt;
    
    @Autowired
    private ProjectInvestorPlanMapperExt projectInvestorPlanMapperExt;
    
    @Autowired
    private ProjectBorrowerSummaryMapper projectBorrowerSummaryMapper;

    @Autowired
    private ProjectLocalService projectLocalService;
    
    @Autowired
    private SpeedLoanDubboService speedLoanDubboService;
	
	@Reference(version = "1.0.0")
	private UserCreditDubboService userCreditDubboService;
	
	@Autowired
	private FeeCalcForRefundService feeCalcForRefundService;
	
	@Autowired
	private PrivacyMasks privacyMasks;	
	
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 可用借款额度变更事件
     * @param userId
     * @param eventType
     */
    public void sendMsgForAviAmountChange(String userId, UsableCreditChangeTypeEventEnum eventType) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    _sendMsgForAviAmountChange(userId, eventType);
                }
            });
        } else {
            _sendMsgForAviAmountChange(userId, eventType);
        }
    }

    /**
     * 可用借款额度变更事件
     * @param userId
     * @param eventType
     */
    private void _sendMsgForAviAmountChange(String userId, UsableCreditChangeTypeEventEnum eventType) {
        try {
            // 剩余可用借款额度
            BigDecimal aviAmount = speedLoanDubboService.getSpeedLoanAviAmount(userId);

            CreditChangeUsableEventReqDTO dto = new CreditChangeUsableEventReqDTO();
            dto.setUserId(userId);
            dto.setCreditChangeTypeEventEnum(eventType);
            dto.setAmount(aviAmount);
            dto.setCreditDate(new Date());
            dto.setUpdateDate(new Date());

            rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE, BizEventRabbitConstant.Key.BIZ_EVENT_CREDIT_CHANGE_USABLE_KEY, dto);

            log.info("【活动-可用借款额度变更】事件消息发送成功，CreditChangeUsableEventReqDTO:{}", JSON.toJSONString(dto));
        } catch (Exception e) {
            log.error("【活动-可用借款额度变更】事件消息发送失败，userId:{}", userId, e);
        }
    }

    /**
     * 流标事件
     * @param projectId
     */
    public void sendMsgForFlowProject(Long projectId, FlowProjectTypeEventEnum flowProjectTypeEventEnum) {
        try {
            log.info("标签系统流标事件,标的ID={},流标类型={}", projectId, flowProjectTypeEventEnum);
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        _sendMsgForFlowProject(projectId, flowProjectTypeEventEnum);
                    }
                });
            } else {
                _sendMsgForFlowProject(projectId, flowProjectTypeEventEnum);
            }
        }catch (Exception e){
            log.error("标签系统流标事件,标的ID={},流标类型={},发生系统异常,原因={}", projectId, flowProjectTypeEventEnum,e);
        }
    }

    /**
     * 流标事件
     * @param projectId
     */
    public void _sendMsgForFlowProject(Long projectId, FlowProjectTypeEventEnum flowProjectTypeEventEnum) {
        ProjectDTO projectDTO=projectLocalService.selectProjectById(projectId);
        FlowProjectEventReqDTO flowProjectEventReqDTO=new FlowProjectEventReqDTO();
        Date now=new Date();
        flowProjectEventReqDTO.setFlowDate(now);
        flowProjectEventReqDTO.setFlowProjectTypeEventEnum(flowProjectTypeEventEnum);
        flowProjectEventReqDTO.setProjectId(projectDTO.getProjectId());
        flowProjectEventReqDTO.setProjectStatusEventEnum(ProjectStatusEventEnum.enumOf(projectDTO.getStatus()));
        flowProjectEventReqDTO.setProjectSubStatusEventEnum(ProjectSubStatusEventEnum.enumOf(projectDTO.getSubStatus()));
        flowProjectEventReqDTO.setUpdateDate(now);
        flowProjectEventReqDTO.setUserId(projectDTO.getBorrowUserId());

        log.info("标签系统流标事件,标的ID={},流标类型={},MQ请求参数={}",projectId,flowProjectTypeEventEnum,JSON.toJSONString(flowProjectEventReqDTO));
        rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE, BizEventRabbitConstant.Key.BIZ_EVENT_FLOW_PROJECT_KEY, flowProjectEventReqDTO);

    }
    
	/**
	 * 借款满标-通知活动中心
	 * 
	 * @param projectId
	 */
	public void fullBorrowEventNotify(Long projectId) {
		log.info("借款满标-通知活动中心，ProjectId:{}", projectId);
		try {
			switchMaster();
			
			Project project = projectMapper.selectByPrimaryKey(projectId);
			if (project == null) {
				log.error("借款满标-通知活动中心异常，异常原因：项目不存在！，ProjectId={}", projectId);
				return;
			}			
			
			FullBorrowEventReqDTO fullBorrowEventReqDTO = new FullBorrowEventReqDTO();
			
			// 用户信息
			fullBorrowEventReqDTO.setUserId(project.getBorrowUserId());
			if (StringUtils.isNotEmpty(project.getBorrowIdCard())) {
				String borrowIdCard = privacyMasks.decryptPrivacy(project.getBorrowIdCard());
				fullBorrowEventReqDTO.setAge(IdCardUtils.getAgeByIdCard(borrowIdCard));
				fullBorrowEventReqDTO.setAddress(IdCardUtils.getProvinceByIdCard(borrowIdCard));
			}
			
			// 授信额度
			UserSpeedCreditInfoDTO userSpeedCreditInfoDTO = userCreditDubboService.getUserSpeedCreditInfo(project.getBorrowUserId());
			if (userSpeedCreditInfoDTO != null && userSpeedCreditInfoDTO.getCreditTotalAmount() != null) {
				fullBorrowEventReqDTO.setCreditAmount(userSpeedCreditInfoDTO.getCreditTotalAmount());		
			} else {
				fullBorrowEventReqDTO.setCreditAmount(BigDecimal.ZERO);
			}
			
			// 标的信息
			fullBorrowEventReqDTO.setProjectId(projectId);
			fullBorrowEventReqDTO.setAmount(project.getContractAmount());
			fullBorrowEventReqDTO.setApplyDate(project.getCreateTime());
			fullBorrowEventReqDTO.setProvince(project.getLoanProvince());
			fullBorrowEventReqDTO.setCity(project.getLoanCity());
			fullBorrowEventReqDTO.setArea(project.getLoanArea());
			fullBorrowEventReqDTO.setApplyAddress(null); // 详细地址没有
			fullBorrowEventReqDTO.setProjectTypeEnum(com.niiwoo.activity.event.enums.ProjectTypeEnum.valueOf(project.getType()));
			fullBorrowEventReqDTO.setDeadline(project.getDeadline());
			fullBorrowEventReqDTO.setDeadlineUnitEnum(DeadlineUnitEnum.valueOf(project.getDeadlineUnit()));
			fullBorrowEventReqDTO.setRepaymentTypeEnum(com.niiwoo.activity.event.enums.RepaymentTypeEnum.valueOf(project.getRepaymentType()));
			fullBorrowEventReqDTO.setFullSuccessDate(project.getFullSuccessTime());
			fullBorrowEventReqDTO.setProjectStatusEventEnum(ProjectStatusEventEnum.enumOf(project.getStatus()));
			fullBorrowEventReqDTO.setProjectSubStatusEventEnum(ProjectSubStatusEventEnum.enumOf(project.getSubStatus()));
			fullBorrowEventReqDTO.setExchangeProjectEventEnum(ExchangeProjectEventEnum.valueOf(project.getIsExchangeProject()));
			fullBorrowEventReqDTO.setFromSourceEventEnum(ProjectFromSourceEventEnum.valueOf(project.getFromSource()));
	
			// 历史借款情况
			List<Byte> fullSuccessProjectStatusList = Arrays.asList(ProjectStatusEnum.REPAYING.getStatus(), ProjectStatusEnum.FINISH.getStatus());
			fullBorrowEventReqDTO.setBorrowNum(projectMapperExt.statisticsProjectCountByStatus(project.getBorrowUserId(), null, null));
			fullBorrowEventReqDTO.setFullSuccessNum(projectMapperExt.statisticsProjectCountByStatus(project.getBorrowUserId(), fullSuccessProjectStatusList, null));
			
			// 红包信息
			if (Objects.nonNull(project.getPrizeId())) {
				fullBorrowEventReqDTO.setPrizeYesOrNoEnum(YesOrNoEnum.YES);
				fullBorrowEventReqDTO.setPrizeId(project.getPrizeId());
			} else {
				fullBorrowEventReqDTO.setPrizeYesOrNoEnum(YesOrNoEnum.NO);
			}
			
			// 借款还款详情
			List<ProjectRepaymentDetailDTO> projectRepaymentDetails = Lists.newArrayList();
			BigDecimal chargesAmount = BigDecimal.ZERO;
			
			List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = projectBorrowerPlanNewMapperExt.selectByProjectIdForAmount(projectId);
			for (ProjectBorrowerPlanNewDTO projectBorrowerPlanNewDTO : projectBorrowerPlanNewDTOList) {
				ProjectRepaymentDetailDTO projectRepaymentDetailDTO = new ProjectRepaymentDetailDTO();
				projectRepaymentDetailDTO.setPeriods(projectBorrowerPlanNewDTO.getPeriod());
				projectRepaymentDetailDTO.setPrincipal(projectBorrowerPlanNewDTO.getCapital());
				projectRepaymentDetailDTO.setInterest(projectBorrowerPlanNewDTO.getInterest());
				projectRepaymentDetailDTO.setRefundDate(projectBorrowerPlanNewDTO.getRefundDate());
				projectRepaymentDetailDTO.setPlatformManagerFee(projectBorrowerPlanNewDTO.getManagementFee());
				projectRepaymentDetailDTO.setUpdateDate(projectBorrowerPlanNewDTO.getUpdateTime());
				
				projectRepaymentDetails.add(projectRepaymentDetailDTO);
				
				// 累计标的费用 =利息 +平台管理费＋担保服务费
				chargesAmount = chargesAmount.add(projectBorrowerPlanNewDTO.getInterest()).add(projectBorrowerPlanNewDTO.getManagementFee()).add(projectBorrowerPlanNewDTO.getGuaranteeFee());
			}
			fullBorrowEventReqDTO.setProjectRepaymentDetails(projectRepaymentDetails);
			fullBorrowEventReqDTO.setChargesAmount(chargesAmount);
			
			// 投资回款详情
			List<InvestorBackPaymentDetailDTO> investorBackPaymentDetails = Lists.newArrayList();
			List<ProjectInvestOrder> projectInvestOrderList = projectInvestOrderMapperExt.queryProjectInvestOrderListOrderByCreateTimeAscByProjectId(projectId);
			for (ProjectInvestOrder projectInvestOrder : projectInvestOrderList) {
				// 已取消的直接跳过
				if (ProjectInvestOrderStatusEnum.CANCEL.getValue() == projectInvestOrder.getStatus()) {
					continue;
				}
				
				List<ProjectInvestorPlan> projectInvestorPlanList = projectInvestorPlanMapperExt.listByInvestOrder(projectInvestOrder.getId());
				for (ProjectInvestorPlan projectInvestorPlan : projectInvestorPlanList) {
					InvestorBackPaymentDetailDTO investorBackPaymentDetailDTO = new InvestorBackPaymentDetailDTO();
					investorBackPaymentDetailDTO.setProjectId(projectId);
					investorBackPaymentDetailDTO.setInvestDate(projectInvestOrder.getCreateTime());
					investorBackPaymentDetailDTO.setInvestorId(projectInvestorPlan.getId());
					investorBackPaymentDetailDTO.setPeriods(projectInvestorPlan.getCurrentPeriod());
					investorBackPaymentDetailDTO.setInvestAmount(projectInvestOrder.getAmount());
					investorBackPaymentDetailDTO.setRevenue(projectInvestorPlan.getInterest());
					investorBackPaymentDetailDTO.setBackDate(projectInvestorPlan.getReceivedDate());
					investorBackPaymentDetailDTO.setPrizeId(projectInvestOrder.getPrizeId());
					investorBackPaymentDetailDTO.setInvestTypeEventEnum(InvestTypeEventEnum.valueOf(projectInvestOrder.getType()));
					
					investorBackPaymentDetails.add(investorBackPaymentDetailDTO);
				}
			}
			fullBorrowEventReqDTO.setInvestorBackPaymentDetails(investorBackPaymentDetails);
			fullBorrowEventReqDTO.setUpdateDate(new Date());
	
			// 发送MQ消息 
			log.info("借款满标-通知活动中心， Msg:{}", JSONObject.toJSONString(fullBorrowEventReqDTO));
			rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE,
					BizEventRabbitConstant.Key.BIZ_EVENT_FULL_BORROW_KEY, fullBorrowEventReqDTO);
			
			log.info("借款满标-通知活动中心成功, ProjectId:{}", projectId);
		} catch (Exception e) {
			log.error("借款满标-通知活动中心异常，异常原因：{}， ProjectId:{}", e.getMessage(), projectId, e);
		}
	}

	/**
	 * 投资满标-通知活动中心
	 * 
	 * @param projectId
	 */
	public void investEventNotify(Long projectId) {
		log.info("投资满标-通知活动中心，ProjectId:{}", projectId);
		try {
			Date currentDate = new Date();
			switchMaster();
			// 查询基础数据
			Project project = projectMapper.selectByPrimaryKey(projectId);
			if (project == null) {
				log.error("投资满标-通知活动中心异常，异常原因：项目不存在！，ProjectId={}", projectId);
				return;
			}
			
			List<ProjectInvestOrder> projectInvestOrderList = projectInvestOrderMapperExt.queryProjectInvestOrderListOrderByCreateTimeAscByProjectId(project.getProjectId());
			
			// 构建MQ信息主体
			for (ProjectInvestOrder projectInvestOrder : projectInvestOrderList) {
				
				// 已取消的直接跳过
				if (ProjectInvestOrderStatusEnum.CANCEL.getValue() == projectInvestOrder.getStatus()) {
					continue;
				}
				
				InvestEventReqDTO investEventReqDTO = new InvestEventReqDTO();
				investEventReqDTO.setUserId(projectInvestOrder.getUserId());
				investEventReqDTO.setProjectId(project.getProjectId());
				investEventReqDTO.setProjectName(project.getTitle());
				investEventReqDTO.setProjectType(com.niiwoo.activity.event.enums.ProjectTypeEnum.valueOf(project.getType()));
				investEventReqDTO.setDeadline(project.getDeadline());
				investEventReqDTO.setDeadlineUnit(DeadlineUnitEnum.valueOf(project.getDeadlineUnit()));
				investEventReqDTO.setRepaymentType(com.niiwoo.activity.event.enums.RepaymentTypeEnum.valueOf(project.getRepaymentType()));
				investEventReqDTO.setInvestorId(projectInvestOrder.getId());
				investEventReqDTO.setInvestAmount(projectInvestOrder.getAmount());
				investEventReqDTO.setInvestProfit(projectInvestOrder.getInterest());
				investEventReqDTO.setInvestTime(projectInvestOrder.getCreateTime());
				investEventReqDTO.setFullSuccessTime(project.getFullSuccessTime());
				//手动网关归属 手动投资
				if(Byte.valueOf("4").equals(projectInvestOrder.getType())) {
					investEventReqDTO.setInvestTypeEventEnum(InvestTypeEventEnum.MANUAL);
				}else {
					investEventReqDTO.setInvestTypeEventEnum(InvestTypeEventEnum.valueOf(projectInvestOrder.getType()));
				}
				investEventReqDTO.setChannelCode(project.getChannelCode());
				if (Objects.nonNull(projectInvestOrder.getPrizeId())) {
					investEventReqDTO.setPrizeYesOrNoEnum(YesOrNoEnum.YES);
					investEventReqDTO.setPrizeTypeEventEnum(UserPrizeTypeEventEnum.valueOf(projectInvestOrder.getPrizeTypteId()));
					investEventReqDTO.setPrizeId(projectInvestOrder.getPrizeId());
				} else {
					investEventReqDTO.setPrizeYesOrNoEnum(YesOrNoEnum.NO);
				}
				investEventReqDTO.setUpdateDate(currentDate);
				investEventReqDTO.setIsThisUserFullProject(YesOrNoEnum.valueOf(projectInvestOrder.getIsFull()));
				log.info("投资满标-通知活动中心， Msg:{}", JSONObject.toJSONString(investEventReqDTO));
				rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE, BizEventRabbitConstant.Key.BIZ_EVENT_INVEST_KEY, investEventReqDTO);
			}
			log.info("投资满标-通知活动中心成功，ProjectId:{}", projectId);
		} catch (Exception e) {
			log.error("投资满标-通知活动中心异常，异常原因：{}， ProjectId:{}", e.getMessage(), projectId, e);
		}			
	}
	
	/**
	 * 项目逾期-通知活动中心
	 * @param tradeBatchTransOrderDTO
	 */
	public void sendOverDueMqMsgToActivity(TradeBatchTransOrderDTO tradeBatchTransOrderDTO) {
		log.info("项目逾期-通知活动中心，ProjectId={}", tradeBatchTransOrderDTO.getProjectId());
		try {
			switchMaster();
			
			Project project = projectMapper.selectByPrimaryKey(tradeBatchTransOrderDTO.getProjectId());
			if (project == null) {
				log.error("项目逾期-通知活动中心异常，异常原因：项目不存在！，ProjectId={}", tradeBatchTransOrderDTO.getProjectId());
				return;
			}			
			
			ProjectBorrowerSummary projectBorrowerSummary = projectBorrowerSummaryMapper.selectByPrimaryKey(tradeBatchTransOrderDTO.getProjectId());
			if (projectBorrowerSummary == null) {
				log.error("项目逾期-通知活动中心异常，异常原因：还款摘要记录为空！，ProjectId={}", tradeBatchTransOrderDTO.getProjectId());
				return;
			}
			
			if (!RepayStatusEnum.OVERDUE.getCode().equals(projectBorrowerSummary.getRepayStatus())
					&& !RepayStatusEnum.BADLOANS.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
				log.error("项目逾期-通知活动中心异常，异常原因：项目状态不匹配！，ProjectId={}", tradeBatchTransOrderDTO.getProjectId());
				return;
			}
			
			// 构建MQ信息内容
			OverdueProjectEventReqDTO overdueProjectEventReqDTO = new OverdueProjectEventReqDTO();
	
			// 基础数据
			overdueProjectEventReqDTO.setProjectId(projectBorrowerSummary.getProjectId());
			overdueProjectEventReqDTO.setUserId(projectBorrowerSummary.getBorrowerUserId());
			overdueProjectEventReqDTO.setTotalPeriods(projectBorrowerSummary.getTotalPeriod());
			overdueProjectEventReqDTO.setCurrentPeriods(projectBorrowerSummary.getCurrentPeriod());
			overdueProjectEventReqDTO.setOverdueStartDate(projectBorrowerSummary.getRefundDate());
			overdueProjectEventReqDTO.setUpdateDate(projectBorrowerSummary.getPenaltyUpdateDate());
			overdueProjectEventReqDTO.setProjectStatusEventEnum(ProjectStatusEventEnum.enumOf(project.getStatus()));
			overdueProjectEventReqDTO.setProjectSubStatusEventEnum(ProjectSubStatusEventEnum.enumOf(project.getSubStatus()));
			
			// 标的历史最高逾期天数
			Integer overdueDay = projectBorrowerPlanNewMapperExt.selectMaxOverdueDayForHistory(projectBorrowerSummary.getProjectId(), projectBorrowerSummary.getBorrowerUserId());
			overdueProjectEventReqDTO.setOverdueDay(overdueDay);
			
			// 逾期金额计算
			RefundStateDTO refundStateDTO = feeCalcForRefundService.caculateAmountRepaymentForAPP(project.getProjectId(), com.niiwoo.civet.base.enums.RefundTypeEnum.IMMEDIATELY);
			
			overdueProjectEventReqDTO.setOverduePrincipal(refundStateDTO.getCapital());
			overdueProjectEventReqDTO.setOverdueInterest(refundStateDTO.getInterest());
			overdueProjectEventReqDTO.setGuaranteFee(refundStateDTO.getGuaranteeFee());
			overdueProjectEventReqDTO.setServiceFee(refundStateDTO.getManageFee());
			overdueProjectEventReqDTO.setOverdueFine(refundStateDTO.getPenaltyFee());

			log.info("项目逾期-通知活动中心，Msg:{}", JSONObject.toJSONString(overdueProjectEventReqDTO));
			rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE,
					BizEventRabbitConstant.Key.BIZ_EVENT_OVERDUE_PROJECT_KEY, overdueProjectEventReqDTO);
			
			log.info("项目逾期-通知活动中心成功，ProjectId:{}", tradeBatchTransOrderDTO.getProjectId());
		} catch (Exception e) {
			log.error("项目逾期-通知活动中心异常，异常原因：{}， ProjectId:{}", e.getMessage(), tradeBatchTransOrderDTO.getProjectId(), e);
		}			
	}
	
	/**
	 * 项目变更事件发送（给活动）
	 * @param userId
	 * @param updateDate
	 * @param projectId
	 * @param projectStatusEventEnum
	 * @param projectSubStatusEventEnum
	 */
	public void sendProjectStatusChangeEvent(String userId, Date updateDate, Long projectId, ProjectStatusEventEnum projectStatusEventEnum, ProjectSubStatusEventEnum projectSubStatusEventEnum) {
		try {
			TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
				@Override
				public void afterCommit() {
					super.afterCommit();
					ProjectStatusChangeEventReqDTO reqDTO = new ProjectStatusChangeEventReqDTO();
					reqDTO.setProjectStatusEventEnum(projectStatusEventEnum);
					reqDTO.setProjectId(projectId);
					reqDTO.setProjectSubStatusEventEnum(projectSubStatusEventEnum);
					reqDTO.setUpdateDate(updateDate);
					reqDTO.setUserId(userId);
					log.info("还款回调-项目状态变更事务已提交，项目变更事件发送（给活动）,ProjectStatusChangeEventReqDTO={}", JSONObject.toJSONString(reqDTO));
					rabbitTemplate.convertAndSend(BizEventRabbitConstant.Exchange.BIZ_EVENT_DIRECT_EXCHANGE, BizEventRabbitConstant.Key.BIZ_EVENT_PROJECT_STATUS_CHANGE_KEY, reqDTO);
				}
			});
		} catch (Exception e) {
			log.error("send to activity projectStatusChangeEvent failed.", e);
		}
	}
	
	/**
	 * 切换到主库
	 */
	public void switchMaster() {
		if (!HintManagerHolder.isMasterRouteOnly()) {
			HintManager hintManager = HintManager.getInstance();
			hintManager.setMasterRouteOnly();
		}
	}
}